<template>
  <div class="addresses-container">
    <el-card class="addresses-card">
      <template #header>
        <div class="card-header">
          <h2>收货地址管理</h2>
          <el-button type="primary" @click="openAddressDialog()">
            <el-icon>
              <Plus />
            </el-icon>新增地址
          </el-button>
        </div>
      </template>

      <!-- 地址列表 -->
      <div v-if="addresses.length > 0" class="address-list">
        <el-card v-for="(address, index) in addresses" :key="index" class="address-item" shadow="hover">
          <div class="address-content">
            <div class="address-info">
              <div class="address-header">
                <span class="address-name">{{ address.name }}</span>
                <span class="address-phone">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault" type="success" size="small">默认地址</el-tag>
              </div>
              <div class="address-detail">
                {{ formatAddress(address) }}
              </div>
            </div>
            <div class="address-actions">
              <el-button type="primary" link @click="openAddressDialog(address, index)">
                <el-icon>
                  <EditPen />
                </el-icon>编辑
              </el-button>
              <el-button type="danger" link @click="deleteAddress(index)">
                <el-icon>
                  <Delete />
                </el-icon>删除
              </el-button>
              <el-button v-if="!address.isDefault" type="success" link @click="setDefaultAddress(index)">
                设为默认
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="暂无收货地址">
        <el-button type="primary" @click="openAddressDialog()">添加地址</el-button>
      </el-empty>
    </el-card>

    <!-- 地址编辑对话框 -->
    <el-dialog v-model="addressDialogVisible" :title="isEdit ? '编辑收货地址' : '新增收货地址'" width="500px">
      <el-form ref="addressFormRef" :model="addressForm" :rules="addressRules" label-width="80px"
        label-position="right">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="所在地区" prop="region">
          <el-cascader v-model="addressForm.region" :options="regionOptions" placeholder="请选择省/市/区" clearable />
        </el-form-item>

        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="addressForm.detailAddress" type="textarea" rows="3"
            placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等" />
        </el-form-item>

        <el-form-item label="邮政编码" prop="postalCode">
          <el-input v-model="addressForm.postalCode" placeholder="请输入邮政编码" />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认收货地址</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, EditPen, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 地址列表
const addresses = ref([])

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    const res = await request.get(`/addresses/user/${userInfo.id}`)
    if (res && res.code === 200 && res.data) {
      addresses.value = res.data
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 地址表单
const addressFormRef = ref(null)
const addressDialogVisible = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)

// 表单数据
const addressForm = reactive({
  name: '',
  phone: '',
  region: [],
  detailAddress: '',
  postalCode: '',
  isDefault: false
})

// 表单验证规则
const addressRules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  postalCode: [
    { pattern: /^\d{6}$/, message: '请输入正确的邮政编码', trigger: 'blur' }
  ]
}

// 地区选项（简化版）
const regionOptions = [
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' },
          { value: '朝阳区', label: '朝阳区' },
          { value: '海淀区', label: '海淀区' },
          { value: '丰台区', label: '丰台区' }
        ]
      }
    ]
  },
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' },
          { value: '长宁区', label: '长宁区' },
          { value: '静安区', label: '静安区' },
          { value: '浦东新区', label: '浦东新区' }
        ]
      }
    ]
  },
  {
    value: '广东省',
    label: '广东省',
    children: [
      {
        value: '广州市',
        label: '广州市',
        children: [
          { value: '越秀区', label: '越秀区' },
          { value: '荔湾区', label: '荔湾区' },
          { value: '海珠区', label: '海珠区' },
          { value: '天河区', label: '天河区' }
        ]
      },
      {
        value: '深圳市',
        label: '深圳市',
        children: [
          { value: '福田区', label: '福田区' },
          { value: '南山区', label: '南山区' },
          { value: '罗湖区', label: '罗湖区' },
          { value: '宝安区', label: '宝安区' }
        ]
      }
    ]
  }
]

// 格式化地址
const formatAddress = (address) => {
  if (address.region && Array.isArray(address.region)) {
    return `${address.region.join(' ')} ${address.detailAddress} ${address.postalCode || ''}`
  } else {
    return `${address.province} ${address.city} ${address.district} ${address.detailAddress} ${address.postalCode || ''}`
  }
}

// 打开地址对话框
const openAddressDialog = (address, index) => {
  resetForm()

  if (address) {
    // 编辑模式
    isEdit.value = true
    editIndex.value = index
    Object.assign(addressForm, address)
  } else {
    // 新增模式
    isEdit.value = false
    editIndex.value = -1
  }

  addressDialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }

  // 重置表单数据
  Object.assign(addressForm, {
    name: '',
    phone: '',
    region: [],
    detailAddress: '',
    postalCode: '',
    isDefault: false
  })
}

// 保存地址
const saveAddress = async () => {
  if (!addressFormRef.value) return

  try {
    await addressFormRef.value.validate()

    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    // 创建地址对象
    const addressData = {
      userId: userInfo.id,
      name: addressForm.name,
      phone: addressForm.phone,
      province: addressForm.region[0],
      city: addressForm.region[1],
      district: addressForm.region[2],
      detailAddress: addressForm.detailAddress,
      postalCode: addressForm.postalCode,
      isDefault: addressForm.isDefault ? 1 : 0
    }

    let res
    if (isEdit.value) {
      // 编辑模式
      const currentAddress = addresses.value[editIndex.value]
      res = await request.put(`/addresses/${currentAddress.id}`, addressData)
    } else {
      // 新增模式
      res = await request.post('/addresses', addressData)
    }

    if (res && res.code === 200) {
      ElMessage.success(isEdit.value ? '地址修改成功' : '地址添加成功')
      addressDialogVisible.value = false
      fetchAddresses() // 重新获取地址列表
    } else {
      ElMessage.error(isEdit.value ? '地址修改失败' : '地址添加失败')
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('保存地址失败')
  }
}

// 删除地址
const deleteAddress = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除该收货地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const address = addresses.value[index]
    const res = await request.delete(`/addresses/${address.id}`)

    if (res && res.code === 200) {
      ElMessage.success('地址删除成功')
      fetchAddresses() // 重新获取地址列表
    } else {
      ElMessage.error('地址删除失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error('地址删除失败')
    }
  }
}

// 设置默认地址
const setDefaultAddress = async (index) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    const address = addresses.value[index]
    const res = await request.put(`/addresses/${address.id}/default?userId=${userInfo.id}`)

    if (res && res.code === 200) {
      ElMessage.success('默认地址设置成功')
      fetchAddresses() // 重新获取地址列表
    } else {
      ElMessage.error('设置默认地址失败')
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

// 页面初始化
onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped>
.addresses-container {
  padding: 20px;
}

.addresses-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.address-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-header {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.address-name {
  font-size: 16px;
  font-weight: 500;
}

.address-phone {
  color: #606266;
}

.address-detail {
  color: #606266;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 10px;
}

/* 深色模式适配 */
html.dark .address-phone,
html.dark .address-detail {
  color: #e5eaf3;
}

html.dark .address-item {
  border-color: #363637;
}

html.dark .address-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}
</style>